package com.xx.task;

import com.xx.dk.tbsalling.aismessages.ais.messages.handler.DynamicDataReportHandler;
import com.xx.util.ProtobufBatchSender;
import com.xx.web.service.MgTrackService;
import com.xx.websocket.server.TrackPushServer;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import java.nio.ByteBuffer;

/**
 * @author fmy
 * @version 1.0
 * @ClassName": TrackPush
 * @Description:
 * @Date": 2023/4/11 13:15
 * @since JDK 1.8
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class TrackPush {

    private final TaskScheduler taskScheduler;
    private final MgTrackService mgTrackService;

    //private final LimitedSizeMap<String, ShipOuterClass.Ship> trackMap = new LimitedSizeMap<>(10);
    @Bean
    public void push() {
        Trigger trigger = new CronTrigger("0/3 * * * * ?");
        taskScheduler.schedule(() -> {
            if (DynamicDataReportHandler.ships.size() > 0) {
                //synchronized (CommonHandler.ships) {
                    if (TrackPushServer.webSocketSet.size() > 0) {
                        //ProtobufBatchSender.sendProtobufBytesBatch(ZmqClient.ships);
                        ByteBuffer buffer = ProtobufBatchSender.sendProtobufBatch(DynamicDataReportHandler.ships);
                        TrackPushServer.sendAllMessage(buffer);
                        DynamicDataReportHandler.ships.clear();
                    } else if (DynamicDataReportHandler.ships.size() > 100) {
                        DynamicDataReportHandler.ships.clear();
                    }
                //}
            }
            if (DynamicDataReportHandler.trackList.size() > 100) {
                synchronized (DynamicDataReportHandler.trackList) {
                    mgTrackService.batchSave(DynamicDataReportHandler.trackList);
                    DynamicDataReportHandler.trackList.clear();
                }
            }
        }, trigger);
    }
}
